﻿using DzInfo.Tools;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.BusinessService;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.FormPlugIn.ShengLian
{
    [Description("盛联单据插件"), HotUpdate]
    public class ShengLianBillPlugIn : AbstractBillPlugIn
    {
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            decimal qty = Convert.ToDecimal(this.Model.DataObject["FQty"]);
            string shengLianLiaoHao = "F_POSW_MaterialId";
            if (e.Field.Key.Equals(shengLianLiaoHao))
            {
                //var oldValue = e.OldValue;
                int newValue = Convert.ToInt32(e.NewValue);
                // 执行查询
                var explorer = new BomExplorer();
                var bomItems = explorer.ExploreBom(newValue, this.Context);
                //DynamicObjectCollection bomItems = GetBomItems(newValue);
                if (bomItems.Count == 0) { return; }
                this.Model.DeleteEntryData("FEntity");
                this.Model.DeleteEntryRow("FEntity", 0);
                this.Model.BatchCreateNewEntryRow("FEntity", bomItems.Count);
                for (int i = 0; i < bomItems.Count; i++)
                {
                    this.Model.SetItemValueByID("F_POSW_DMaterialId", bomItems[i]["FMATERIALID"], i);
                    this.Model.SetValue("F_POSW_YL", bomItems[i]["YL"], i);
                    this.Model.SetValue("F_POSW_TTL", bomItems[i]["FMATERIALTYPE"], i);
                    this.Model.SetValue("F_POSW_ZYL", Convert.ToDecimal(bomItems[i]["YL"]) * qty, i);
                }
                this.Model.ClearNoDataRow();
                this.View.UpdateView();
            }
            if (e.Field.Key.Equals("F_POSW_DMaterialId"))
            {
                int matId = Convert.ToInt32(e.NewValue);
                decimal newPrice = GetMatPrice(matId);
                decimal invQty = GetInvQty(matId);
                this.Model.SetValue("F_POSW_Price", newPrice, e.Row);
                this.Model.SetValue("F_QKBJ_Qty_JSKC", invQty, e.Row);
            }
            if (e.Field.Key.Equals("F_POSW_YL"))
            {
                Entity entity = this.Model.BillBusinessInfo.GetEntity("FEntity");
                decimal price = Convert.ToDecimal(this.Model.GetEntityDataObject(entity, e.Row)["F_POSW_Price"]);
                this.Model.SetValue("F_POSW_XJ", price * Convert.ToDecimal(e.NewValue), e.Row);
            }
            if (e.Field.Key.Equals("F_POSW_XJ"))
            {
                Entity entity = this.Model.BillBusinessInfo.GetEntity("FEntity");
                var rows = this.Model.GetEntityDataObject(entity);
                var clxj = rows.Select(s => s["F_POSW_XJ"]).Sum(m => Convert.ToDecimal(m));
                this.Model.SetValue("F_POSW_CLHJ", clxj);
            }
            if (e.Field.Key.Equals("F_POSW_BJXJ"))
            {
                Entity entity = this.Model.BillBusinessInfo.GetEntity("FEntity");
                var rows = this.Model.GetEntityDataObject(entity);
                var clxj = rows.Select(s => s["F_POSW_BJXJ"]).Sum(m => Convert.ToDecimal(m));
                this.Model.SetValue("F_POSW_CLHJ2", clxj);
                this.View.UpdateView("F_POSW_CLHJ2");
            }
            if (e.Field.Key.Equals("F_POSW_CLHJ2") || e.Field.Key.Equals("F_POSW_JGCB") || e.Field.Key.Equals("F_POSW_GLCB") || e.Field.Key.Equals("F_POSW_YSBZCB"))
            {
                var obj = this.Model.DataObject;
                this.Model.SetValue("F_POSW_CBHJBHS", Convert.ToDecimal(obj["F_POSW_CLHJ2"]) + Convert.ToDecimal(obj["F_POSW_JGCB"]) + Convert.ToDecimal(obj["F_POSW_GLCB"]) + Convert.ToDecimal(obj["F_POSW_YSBZCB"]));
            }
            if (e.Field.Key.Equals("F_POSW_CBHJBHS") && Convert.ToDecimal(this.Model.DataObject["F_POSW_WSBJ"]) > 0)
            {
                var obj = this.Model.DataObject;
                this.Model.SetValue("F_POSW_MLL", (Convert.ToDecimal(obj["F_POSW_WSBJ"]) - Convert.ToDecimal(obj["F_POSW_CBHJBHS"])) / Convert.ToDecimal(obj["F_POSW_WSBJ"]));
            }
            if (e.Field.Key.Equals("F_POSW_WSBJ") || e.Field.Key.Equals("F_POSW_SL"))
            {
                var rate = this.Model.DataObject["F_POSW_SL"] as DynamicObject;
                decimal rateValue = GetRateId(rate);
                var jshj = Convert.ToDecimal(this.Model.DataObject["F_POSW_WSBJ"]) * (1M + rateValue / 100);
                this.Model.SetValue("F_POSW_JSHJ", jshj);
                this.View.UpdateView("F_POSW_JSHJ");
            }
            //this.View.UpdateView();
        }

        private decimal GetInvQty(int matId)
        {
            string sql = string.Format(@"/*dialect*/ 
            select sum(t0.FBASEQTY) qty from T_STK_INVENTORY t0
            join T_BD_STOCK t1 on t1.FSTOCKID=t0.FSTOCKID
            where t0.FMATERIALID={0} and (t1.FNUMBER='001' or t1.FNUMBER='005')
            group by t0.FMATERIALID ", matId);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        /// <summary>
        /// 获取税率值
        /// </summary>
        /// <param name="rate"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private decimal GetRateId(DynamicObject rate)
        {
            int rateId = rate == null ? 0 : Convert.ToInt32(rate["id"]);
            string sql = string.Format(@"/*dialect*/ 
            SELECT FTAXRATE FROM T_BD_TAXRATE WHERE FID={0} ", rateId);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        /// <summary>
        /// 根据材料ID获取最新的采购入库单价，如果没有采购入库价返回0
        /// </summary>
        /// <param name="matId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private decimal GetMatPrice(int matId)
        {
            string sql = string.Format(@"/*dialect*/ 
            select top 1 t2.FPRICE 
            from T_PUR_POORDER t0
            join T_PUR_POORDERENTRY t1 on t1.FID=t0.FID
            join T_PUR_POORDERENTRY_F t2 on t2.FENTRYID=t1.FENTRYID
            where t1.FMATERIALID={0} and t2.FPRICE>0
            order by t1.FMATERIALID,t0.FDATE DESC ", matId);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        /// <summary>
        /// 根据新的盛联料号查找BOM，如果存在多个BOM，获取日期最新的BOM
        /// </summary>
        /// <param name="newValue"></param>
        /// <returns></returns>
        private DynamicObjectCollection GetBomItems(int newValue)
        {
            string bomVer = GetBomVer(newValue);
            string sql = string.Format(@"/*dialect*/ 
            SELECT T1.FMATERIALID,T1.FNUMERATOR/T1.FDENOMINATOR YL,CASE WHEN T1.FMATERIALTYPE=1 THEN '标准件'  WHEN T1.FMATERIALTYPE=2 THEN '返还件' ELSE '替代件' END FMATERIALTYPE
            FROM T_ENG_BOM T0
            JOIN T_ENG_BOMCHILD T1 ON T1.FID=T0.FID
            WHERE T0.FMATERIALID={0} AND T0.FNUMBER='{1}' ", newValue, bomVer);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }
        /// <summary>
        /// 根据料号查找BOM版本号，返回最新创建日期的版本号
        /// </summary>
        /// <param name="newValue"></param>
        /// <returns></returns>
        private string GetBomVer(int newValue)
        {
            string sql = string.Format(@"/*dialect*/ 
            select FNUMBER from T_ENG_BOM where FMATERIALID={0} ORDER BY FCREATEDATE DESC ", newValue);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc != null && doc.Count > 0)
            {
                return doc.FirstOrDefault()[0].ToString();
            }
            return "";
        }
    }
}
